//
//  FYComposeViewController.swift
//  dugeweibo
//
//  Created by pelesys on 16/8/7.
//  Copyright © 2016年 杜方宜. All rights reserved.
//

import UIKit
import SVProgressHUD
class FYComposeViewController: UIViewController {
    // MARK:-控件属性
 
    @IBOutlet weak var textView: FYComposeTextView!
    
    @IBOutlet weak var PicPickerCollectionView: FYPicPikerCollectionView!
    
    // MARK-懒加载属性
    private lazy  var titleView : FYComposeTitleView = FYComposeTitleView()
    private lazy  var imges : [UIImage] = [UIImage]()
    private lazy  var emotionVc : FYEmoticonController = FYEmoticonController {[weak self] (emotion) in
        //为什么没有提示
        self?.textView.insertEmotion(emotion: emotion)
        self?.textViewDidChange(self!.textView)
     
    }
    // MARK:-约束的属性
    @IBOutlet weak var picPicerViewHCons: NSLayoutConstraint!
    @IBOutlet weak var toolBarBottomCons: NSLayoutConstraint!
    
    //MARK:-系统回调函数
    override func viewDidLoad() {
        //设置代理
        textView.delegate = self
        super.viewDidLoad()
        //设置导航栏
        setupNavigationBar()
        //监听键盘通知 
        setupNOtifications()
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        textView.becomeFirstResponder()
    }
    deinit{
        NotificationCenter.default.removeObserver(self)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
  
}
// MARK:-设置UI界面
extension FYComposeViewController{
    private func setupNavigationBar(){
        //1.设置左右的item
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(closeItemClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .plain, target: self, action: #selector(sendItemClick))
        navigationItem.rightBarButtonItem?.isEnabled = false
        //2.设置标题
        titleView.frame = CGRect(x: 0, y: 0, width: 100, height: 40)
        navigationItem.titleView = titleView
        
        
    }
    private func setupNOtifications(){
        //监听键盘的弹出
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame(noti:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
        //监听添加照片的按钮的点击
        NotificationCenter.default.addObserver(self, selector: #selector(addPhotoClick), name: NSNotification.Name(PicPickerAddPhotoNote), object: nil)
        //监听删除照片的按钮的点击
        NotificationCenter.default.addObserver(self, selector: #selector(removePhoteoClick(noti:)), name: NSNotification.Name(PicPickerRemovePhotoNote), object: nil)
    }
}
// MARK:-事件监听函数
extension FYComposeViewController{
    //返回按钮
    @objc private func closeItemClick(){
        dismiss(animated: true, completion: nil);
    }
    //发送按钮
    @objc private func sendItemClick(){
        //1.键盘退出
        textView.resignFirstResponder()
        //2.获取发送微博的微博正文
        let statusText = textView.getEmotionString()
        //3.定义回调的闭包
        let finishedCallback = { (isSuccess : Bool) -> () in
            if !isSuccess {
                SVProgressHUD.showError(withStatus: "发送微博失败")
                return
            }
            SVProgressHUD.showSuccess(withStatus: "发送微博成功")
            self.dismiss(animated: true, completion: nil)
        }
        //4.获取用户选中的图片
        if let image = imges.first {
            NetworkTools.shareInstance.sendStasus(statusText: statusText, image: image, isSuccess: finishedCallback)
        }else{
            NetworkTools.shareInstance.sendStatus(statusText: statusText, isSuccess: finishedCallback)
        }
    }
    //键盘frame改变
    @objc private func keyboardWillChangeFrame(noti:NSNotification){
        //1.获取动画执行时间
        let duration = noti.userInfo![UIResponder.keyboardAnimationDurationUserInfoKey] as! TimeInterval
        //2.获取键盘最终Y值
        let endFrame = (noti.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let y = endFrame.origin.y
        
        //3.计算工具栏距离底部的间距
        let margin = UIScreen.main.bounds.height - y
        
        //4.执行动画
        toolBarBottomCons.constant = margin
        UIView.animate(withDuration: duration) {
            self.view.layoutIfNeeded()
        }
        
        
    }
    //图片按钮点击事件
    @IBAction func picPickerBtnClick(sender: UIButton) {
        //退出键盘
        textView.resignFirstResponder()
        //执行动画 弹出collectionView
        picPicerViewHCons.constant = UIScreen.main.bounds.height * 0.65
        UIView.animate(withDuration: 0.5) {
            self.view.layoutIfNeeded()
        }
    }
    //表情按钮点击事件
    @IBAction func emoticonBtnClick(sender: UIButton) {
      //1.退出键盘
        textView.resignFirstResponder()
      //2.切换键盘
        textView.inputView = textView.inputView != nil ? nil : emotionVc.view
      //3.弹出键盘
        textView.becomeFirstResponder()
    }
}

// MARK:-添加照片和删除照片的事件
extension FYComposeViewController{
    @objc private func addPhotoClick(){
    //1.判断数据是否可用
        if !UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
            return
        }
     //2.创建图片选择控制器
        let ipc = UIImagePickerController()
     //3.设置照片源
        ipc.sourceType = .photoLibrary
        
     //4.设置代理
        ipc.delegate = self
     //弹出选择照片的控制器
        present(ipc, animated: true, completion: nil)
        
    }
    
    @objc private func removePhoteoClick(noti:NSNotification){
        //1.获取image对象
        guard let imgae = noti.object as? UIImage else{
            return
        }
        //2.获取image对象所在下标值
        guard let index = imges.firstIndex(of: imgae)
            else{
                return
        }
        //3.将图片从数组中删除
        imges.remove(at: index)
        //4.重新赋值collectionview新的数组  修改数据源
        PicPickerCollectionView.images = imges
        
    }
}
// MARK:-UIImagePickerController的代理方法
extension FYComposeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    private func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        //1.获取选中的照片
        let image = info[UIImagePickerController.InfoKey.originalImage.rawValue] as! UIImage
        //2.将选中的照片添加到数组中
        imges.append(image)
        //3.将数组赋值给collevtionview,让collectionView自己去展示数据
        PicPickerCollectionView.images = imges
        //4.退出选中照片控制器
        picker.dismiss(animated: true, completion: nil)
    }
}

// MARK:-UITextVIew的代理方法
extension FYComposeViewController : UITextViewDelegate{
    func textViewDidChange(_ textView: UITextView) {
        self.textView.placeHolderLabel.isHidden = textView.hasText
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        textView.resignFirstResponder()
    }
}
